/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JTicketLinePropEdit.java
 *
 * Created on 2009-8-28, 14:11:01
 */

package com.openbravo.pos.sales;

import cn.ekuma.swing.dialog.AbstractKeyBoardJDialog;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.pos.base.AppLocal;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;

import com.openbravo.pos.util.StringUtils;

/**
 *
 * @author Administrator
 */
public class JTicketLinePropEdit extends AbstractKeyBoardJDialog {
    private List<JList> propLists;
    private JList currenJList;
    private String retProps;
    private boolean isOK;

    /** Creates new form JTicketLinePropEdit */
    public JTicketLinePropEdit(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
    }

    private JTicketLinePropEdit(Dialog dialog, boolean modal) {
       super(dialog, modal);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel2 = new javax.swing.JPanel();
        m_jButtonOK = new javax.swing.JButton();
        m_jButtonCancel = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel4 = new javax.swing.JPanel();
        jBtnToRightOne = new javax.swing.JButton();
        jBtnToLeftOne = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel2.setFocusable(false);
        jPanel2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        m_jButtonOK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_ok.png"))); // NOI18N
        m_jButtonOK.setText(AppLocal.getIntString("Button.OK")); // NOI18N
        m_jButtonOK.setFocusPainted(false);
        m_jButtonOK.setFocusable(false);
        m_jButtonOK.setMargin(new java.awt.Insets(8, 16, 8, 16));
        m_jButtonOK.setRequestFocusEnabled(false);
        m_jButtonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jButtonOKActionPerformed(evt);
            }
        });
        jPanel2.add(m_jButtonOK);

        m_jButtonCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_cancel.png"))); // NOI18N
        m_jButtonCancel.setText(AppLocal.getIntString("Button.Cancel")); // NOI18N
        m_jButtonCancel.setFocusPainted(false);
        m_jButtonCancel.setFocusable(false);
        m_jButtonCancel.setMargin(new java.awt.Insets(8, 16, 8, 16));
        m_jButtonCancel.setRequestFocusEnabled(false);
        m_jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jButtonCancelActionPerformed(evt);
            }
        });
        jPanel2.add(m_jButtonCancel);

        getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH);

        jPanel1.setFocusable(false);
        jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.LINE_AXIS));

        jPanel5.setFocusable(false);
        jPanel5.setLayout(new java.awt.BorderLayout());

        jTabbedPane1.setBorder(javax.swing.BorderFactory.createTitledBorder("F5"));
        jTabbedPane1.setFocusable(false);
        jTabbedPane1.setMinimumSize(new java.awt.Dimension(60, 85));
        jTabbedPane1.setPreferredSize(new java.awt.Dimension(220, 300));
        jTabbedPane1.setRequestFocusEnabled(false);
        jPanel5.add(jTabbedPane1, java.awt.BorderLayout.CENTER);

        jPanel1.add(jPanel5);

        jPanel4.setFocusable(false);
        jPanel4.setPreferredSize(new java.awt.Dimension(50, 159));
        jPanel4.setRequestFocusEnabled(false);
        jPanel4.setLayout(new java.awt.GridBagLayout());

        jBtnToRightOne.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/1rightarrow.png"))); // NOI18N
        jBtnToRightOne.setFocusPainted(false);
        jBtnToRightOne.setFocusable(false);
        jBtnToRightOne.setMargin(new java.awt.Insets(8, 14, 8, 14));
        jBtnToRightOne.setRequestFocusEnabled(false);
        jBtnToRightOne.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnToRightOneActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0);
        jPanel4.add(jBtnToRightOne, gridBagConstraints);

        jBtnToLeftOne.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/1leftarrow.png"))); // NOI18N
        jBtnToLeftOne.setFocusPainted(false);
        jBtnToLeftOne.setFocusable(false);
        jBtnToLeftOne.setMargin(new java.awt.Insets(8, 14, 8, 14));
        jBtnToLeftOne.setRequestFocusEnabled(false);
        jBtnToLeftOne.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnToLeftOneActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0);
        jPanel4.add(jBtnToLeftOne, gridBagConstraints);

        jLabel1.setPreferredSize(new java.awt.Dimension(48, 35));
        jPanel4.add(jLabel1, new java.awt.GridBagConstraints());

        jPanel1.add(jPanel4);

        jPanel3.setFocusable(false);
        jPanel3.setLayout(new java.awt.BorderLayout());

        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
        jScrollPane1.setFocusable(false);

        jList1.setBorder(javax.swing.BorderFactory.createTitledBorder("F6"));
        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        jList1.setMaximumSize(new java.awt.Dimension(150, 85));
        jList1.setPreferredSize(new java.awt.Dimension(120, 150));
        jList1.setRequestFocusEnabled(false);
        jList1.setVerifyInputWhenFocusTarget(false);
        jScrollPane1.setViewportView(jList1);

        jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jPanel1.add(jPanel3);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-524)/2, (screenSize.height-405)/2, 524, 405);
    }// </editor-fold>//GEN-END:initComponents

    private void m_jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jButtonOKActionPerformed
       isOK=true;
       PropListModel rightModel=(PropListModel)jList1.getModel();
       retProps=rightModel.buildProps();
       dispose();

}//GEN-LAST:event_m_jButtonOKActionPerformed

    private void m_jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jButtonCancelActionPerformed
       dispose();
    }//GEN-LAST:event_m_jButtonCancelActionPerformed


    private void jBtnToRightOneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnToRightOneActionPerformed
         JList leftList= getLeftJList();
         String value=(String)leftList.getSelectedValue();
         PropListModel rightModel=(PropListModel)jList1.getModel();
         rightModel.addRow(value);
    }//GEN-LAST:event_jBtnToRightOneActionPerformed

    private void jBtnToLeftOneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnToLeftOneActionPerformed
        int selectIndex=jList1.getSelectedIndex();
        if(selectIndex<0)
            return;
        PropListModel rightModel=(PropListModel)jList1.getModel();
        rightModel.removeRow(selectIndex);
    }//GEN-LAST:event_jBtnToLeftOneActionPerformed

    public static JTicketLinePropEdit getPropEdit(Component parent, String lineProps) throws BasicException {
        Window window = getWindow(parent);
        
        JTicketLinePropEdit myMsg;
        if (window instanceof Frame) {
            myMsg = new JTicketLinePropEdit((Frame) window, true);
        } else {
            myMsg = new JTicketLinePropEdit((Dialog) window, true);
        }
        myMsg.init(lineProps);
        myMsg.applyComponentOrientation(parent.getComponentOrientation());
        return myMsg;
    }

    public String getRetProps(){
        return retProps;
    }

    public boolean isOK(){
        return isOK;
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBtnToLeftOne;
    private javax.swing.JButton jBtnToRightOne;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JButton m_jButtonCancel;
    private javax.swing.JButton m_jButtonOK;
    // End of variables declaration//GEN-END:variables

   private void buildPropPanel(){
       String props=AppLocal.getIntString("app.productext.props");
       if(props==null){
           Toolkit.getDefaultToolkit().beep();
           new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.noproductext.props")).show(this);
           dispose();
       }
       Map<String,ArrayList<String>> propMay=splitProps(props);
       Object[] keySet=propMay.keySet().toArray();
       for(int i=0;i<keySet.length;i++){
           String title=keySet[i].toString();
           ArrayList prop=propMay.get(keySet[i]);
           addPropPanel(title,prop);
       }
   }

   private void addPropPanel(String title,ArrayList propList){
       JPanel tPanel=new JPanel();
       tPanel.setLayout(new java.awt.BorderLayout());
       JScrollPane jScroll=new JScrollPane();
       JList jList=new JList(new PropListModel(propList));
       jScroll.setViewportView(jList);
       tPanel.add(jScroll,BorderLayout.CENTER);
       jTabbedPane1.add(title, tPanel);
       propLists.add(jList);
   }

   private Map<String,ArrayList<String>> splitProps(String propsLine){
       String[] props=propsLine.split(";");
       Map restMap=new HashMap<String,ArrayList<String>>();
       for(String propLine:props){
           String[] propEntry=propLine.split(":");
           restMap.put(propEntry[0],StringUtils.splitProp(propEntry[1]));
       }
       return restMap;
   }


    private void init(String ticketLineExtProp) {
        initComponents();

        retProps=ticketLineExtProp;
        isOK=false;

        propLists=new ArrayList();
        jList1.setModel(new PropListModel(StringUtils.splitProp(ticketLineExtProp)));
        buildPropPanel();

        KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0);
        JRootPane rootPane1 =getRootPane();
        ActionListener actionListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                leftKeyProc();
            }
        };
        rootPane1.registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        stroke = KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0);
        rootPane1 =getRootPane();
        actionListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                rightKeyProc();
            }
        };
        rootPane1.registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);


        stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ADD, 0);
        rootPane1 =getRootPane();
        actionListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                spaceKeyProc();
            }
        };
        rootPane1.registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);


        currenJList=getLeftJList();
        getRootPane().setDefaultButton(m_jButtonOK);   
    }

    private JList getLeftJList(){
          int selectIndex=jTabbedPane1.getSelectedIndex();
          System.out.println("getLeftJlist:"+selectIndex);
          return propLists.get(selectIndex);
    }

     private void leftKeyProc() {
        int selected=jTabbedPane1.getSelectedIndex();
        int count=jTabbedPane1.getComponentCount();
        if(selected==count-1)
            selected=0;
        else
            selected++;
        jTabbedPane1.setSelectedIndex(selected);
        jLabel1.setText("+ -->");
        currenJList=getLeftJList();
        currenJList.requestFocus();
    }

    private void rightKeyProc() {
          currenJList=jList1;
          jLabel1.setText("<-- +");
          currenJList.requestFocus();
    }

    protected void spaceKeyProc(){
        System.out.println(currenJList);
        if(currenJList!=jList1){
            jBtnToRightOneActionPerformed(null);
        }
        else
            jBtnToLeftOneActionPerformed(null);
    }

    @Override
    protected void enterKeyProc() {
        if(m_jButtonOK.isEnabled())
            m_jButtonOKActionPerformed(null);
    }

    @Override
    protected void escapeKeyProc() {
       dispose();
    }

    @Override
    protected void upKeyProc() {
        int i = currenJList.getSelectionModel().getMinSelectionIndex();
        if (i < 0){
            i = currenJList.getModel().getSize() - 1; // No hay ninguna seleccionada
        } else {
            i --;
            if (i < 0) {
                i = 0;
            }
        }

        if ((i >= 0) && (i < currenJList.getModel().getSize())) {
            // Solo seleccionamos si podemos.
            setSelectedIndex(i);
        }
    }

    @Override
    protected void downKeyProc() {
        int i = currenJList.getSelectionModel().getMaxSelectionIndex();
        if (i < 0){
            i =  0; // No hay ninguna seleccionada
        } else {
            i ++;
            if (i >= currenJList.getModel().getSize()) {
                i =currenJList.getModel().getSize() - 1;
            }
        }

        if ((i >= 0) && (i < currenJList.getModel().getSize())) {
            // Solo seleccionamos si podemos.

            setSelectedIndex(i);
        }
    }

     public void setSelectedIndex(int i){
        currenJList.setSelectedIndex(i);

    }

    private class PropListModel extends javax.swing.AbstractListModel{
       ArrayList<String> propList;

       public PropListModel(ArrayList<String> inPropList){
           if(inPropList==null)
               propList=new ArrayList();
           else
               propList=inPropList;
       }

        @Override
        public int getSize() {
            return propList.size();
        }

        @Override
        public Object getElementAt(int index) {
           return propList.get(index);
        }

        public void addRow(String oLine) {
            insertRow(propList.size(), oLine);
        }

        public void insertRow(int index, String oLine) {
            propList.add(index, oLine);
            fireIntervalAdded(this, index, index);
        }

        public void removeRow(int row) {
            propList.remove(row);
            fireIntervalRemoved(this, row, row);
        }

        public ArrayList getList(){
            return propList;
        }

        public void addRow(ArrayList rows){
            propList.addAll(rows);
        }

        public void reset(){
            propList=new ArrayList();
        }

        public String buildProps(){
            return org.apache.commons.lang.StringUtils.join(propList.iterator(), ",");
        }
    }
}
